﻿using HandyControl.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace CommunityToolkitMvvmDemo
{
    /// <summary>
    /// 
    /// </summary>
    public interface IWaitDialog
    {        
        Action Completed { get; set; }
        bool IsSuccessed { get; set; }
    }
    public interface IWaitResult<T>
    {
        T Result { get; set; }
        Action Completed { get; set; } 
        bool IsSuccessed { get; set; }
    }
    public static class DialogGetResultExtension
    {
        public static Task WaitResultAsync<T>(this IWaitResult<T> resultable)
        {
            var dialog = Dialog.Show(resultable);
            if (dialog.IsClosed)
            {
                return Task.CompletedTask;
            }
            var tcs = new TaskCompletionSource();
            dialog.Unloaded += OnUnloaded;
            resultable.Completed += OnCompleted;
            return tcs.Task;

            void OnUnloaded(object sender, RoutedEventArgs e)
            {
                dialog.Unloaded -= OnUnloaded;
                OnCompleted();
            }           
            void OnCompleted()
            {
                try
                {
                    tcs.TrySetResult();                    
                }
                catch(Exception ex)
                {
                    tcs.TrySetException(ex);
                }
                finally
                {
                    dialog.Close();
                }
            }
        }

        public static Task WaitAsync(this IWaitDialog resultable)
        {
            var dialog = Dialog.Show(resultable);
            if (dialog.IsClosed)
            {
                return Task.CompletedTask;
            }
            var tcs = new TaskCompletionSource();
            dialog.Unloaded += OnUnloaded;
            resultable.Completed += OnCompleted;
            return tcs.Task;

            void OnUnloaded(object sender, RoutedEventArgs e)
            {
                dialog.Unloaded -= OnUnloaded;
                OnCompleted();
            }
            void OnCompleted()
            {
                try
                {
                    tcs.TrySetResult();
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
                finally
                {
                    dialog.Close();
                }
            }
        }
        
    }
}
